<template>
  <view class="my-settle-container">
    <view class="radio">
      <radio color="#c00000" :checked="isAllCheck" @click="toggle" />全选
    </view>
    <view>
      合计：
      <text class="amount">￥{{ getSelectAmount }}</text>
    </view>
    <view
      class="btn-settle"
      @click="settle"
      :style="{ 'background-color': getSelectTotal === 0 ? '#ccc' : '#c00000' }"
    >
      结算({{ getSelectTotal }})
    </view>
  </view>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
export default {
  data () {
    return {
      time: 3,
      timer: -1
    }
  },
  computed: {
    ...mapGetters('cart', [
      'getSelectTotal',
      'getSelectAmount',
      'getTotal',
      'getCartList'
    ]),
    ...mapGetters('user', ['getAddress', 'getToken', 'addressStr']),
    isAllCheck () {
      return this.getSelectTotal === this.getTotal
    }
  },
  methods: {
    ...mapMutations('cart', ['updateAllGoodsState']),
    ...mapMutations('user', ['setNavUrl']),
    toggle () {
      this.updateAllGoodsState(!this.isAllCheck)
    },
    // 结算
    async settle () {
      // 判断是否选择了商品
      if (this.getSelectTotal === 0) {
        uni.showToast({
          title: '请选择至少一件商品进行结算~',
          icon: 'none',
          duration: 1000
        })
        return
      }
      // 判断是否选择了收货地址
      if (!this.getAddress) {
        uni.showToast({
          title: '请选择收货地址~',
          icon: 'none',
          duration: 1000
        })
        return
      }
      // 判断是否进行了登录
      if (!this.getToken) {
        this.delayNav()
        return
      }
      // 下单（生成订单）
      // 准备好要提交的参数
      const params = {
        order_price: this.getSelectAmount,
        consignee_addr: this.addressStr,
        goods: this.getCartList
          .filter(item => item.goods_state)
          .map(item => {
            return {
              goods_id: item.goods_id,
              goods_number: item.goods_number,
              goods_price: item.goods_price
            }
          })
      }
      console.log(params)
      const res = await uni.$request({
        url: 'my/orders/create',
        method: 'POST',
        data: params
      })
      console.log('res', res)
      if (res.meta.status !== 200) return
      const { order_number } = res.message
      // 支付
      // 1.获取支付参数
      const res2 = await uni.$request({
        url: 'my/orders/req_unifiedorder',
        method: 'POST',
        data: {
          order_number
        }
      })
      if (res2.meta.status === 200) {
        // 2、调用 uni.requestPayment 这个api，传递五个参数，就会弹出支付框（微信提供的）
        uni.requestPayment({
          ...res2.message.pay,
          success: async result => {
            // 3. 支付成功之后，告知后台，该订单支付成了
            const res3 = await uni.$request({
              url: 'my/orders/chkOrder',
              method: 'POST',
              data: {
                order_number
              }
            })
            if (res3.meta.status === 200) {
              uni.showToast({
                title: 'res3.message',
                icon: 'success',
                mask: true,
                duration: 1000
              })
            }
          },
          fail: ({ errMsg }) => {
            if (errMsg === 'requestPayment:fail cancel') {
              uni.showToast({
                title: '您取消了支付!',
                icon: 'none',
                mask: true,
                duration: 1000
              })
            } else {
              uni.showToast({
                title: '支付失败，请联系客服!',
                icon: 'none',
                mask: true,
                duration: 1000
              })
            }
          }
        })
      }
    },
    // 倒计时，然后跳转到我的页面（登录组件和用户信息组件）
    delayNav () {
      this.showTip(this.time)

      this.timer = setInterval(() => {
        if (this.time <= 1) {
          clearInterval(this.timer)
          this.time = 3

          // 跳转到我的页面
          uni.switchTab({
            url: '/pages/my/index',
            success: () => {
              this.setNavUrl('/pages/cart/index')
            }
          })

          return
        }

        this.time--
        this.showTip(this.time)
      }, 1000)
    },
    showTip (time) {
      uni.showToast({
        title: `您还未登录，${time} 秒之后跳转到登录页面`,
        icon: 'none',
        duration: 1000,
        mask: true
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.my-settle-container {
  position: fixed;
  z-index: 99;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  // 将背景色从 cyan 改为 white
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 5px;
  font-size: 14px;

  .radio {
    display: flex;
    align-items: center;
  }

  .amount {
    color: #c00000;
  }

  .btn-settle {
    height: 50px;
    min-width: 100px;
    // background-color: #c00000;
    color: white;
    line-height: 50px;
    text-align: center;
    padding: 0 10px;
  }
}
</style>
